package com.ajaxw.crawler;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Dispatcher {
	private LinkedList<JobInfo> pool = new LinkedList<JobInfo>();
	private List<JobThread> threads = new ArrayList<JobThread>();
	private int size = 10;
	private int jobNum = 0;

	public int getJobNum() {
		return this.jobNum;
	}

	public Dispatcher() {
		for (int i = 0; i < size; i++) {
			JobThread thread = new JobThread(this);
			this.threads.add(thread);
			thread.start();
		}
	}

	public Dispatcher(int size) {

	}

	public void run(JobInfo task) {
		synchronized (this.pool) {
			this.pool.add(task);
			this.jobNum++;
			this.pool.notify();
		}
	}

	public JobInfo getNext() {
		JobInfo task = null;
		synchronized (this.pool) {
			while (this.pool.isEmpty())
				try {
					this.pool.wait();
				} catch (Exception e) {
					e.printStackTrace();
				}
			task = this.pool.removeFirst();
			this.jobNum--;
		}
		return task;
	}

	public void stop() {
		for (JobThread jThread : threads)
			jThread.terminate();
	}
}
